/**
 * @author 木人心
 * @version 1.0.0
 */
import {
  createRouter,
  createWebHashHistory,
  RouteRecordRaw
} from 'vue-router'
import { RouteModules } from '@/router/type'
import { ObjectUtil } from '@utils/object-util'
import RouterInterceptor from '@/router/interceptor'

// 获取路由分包文件
export const modulesFiles = import.meta.glob<RouteModules>('./modules/*.ts', { eager: true })
export const menuFiles: Record<string, RouteRecordRaw[]> = {}
// 从分包文件中分离出路由配置
const routes = Object.keys(modulesFiles).reduce((routes, modulePath) => {
  const module = modulesFiles[modulePath].default
  if (module.isMenu) {
    const moduleName = modulePath.replace(/^\.\/modules\/(.*)\.\w+$/, '$1')
    menuFiles[moduleName] = ObjectUtil.deepCopy(module.routes)
  }
  return routes.concat(module.routes)
}, [] as RouteRecordRaw[])

// 创建路由实例
const router = createRouter({ history: createWebHashHistory(), routes })

// 添加路由拦截器
RouterInterceptor.use(router)

export default router
